package org.ewaf.framework.struts2.velocity;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.velocity.tools.view.ToolboxManager;
import org.apache.velocity.tools.view.XMLToolboxManager;
import org.springframework.core.io.ClassPathResource;

import org.apache.struts2.StrutsConstants;
import org.apache.struts2.config.DefaultSettings;

/**
 * WebWork的VelocityManager默认采用Web应用根路径下的toolbox.xml初始化toolbox。 将其修改成支持Class
 * Path方式装载toolbox.xml，并且将ToolboxManager暴露出来， 以便非界面代码也能使用toolbox中的工具类。
 */
public class VelocityManagerEx extends
		org.apache.struts2.views.velocity.VelocityManager {

	private final static Logger log = Logger.getLogger(VelocityManagerEx.class);
	private static VelocityManagerEx instance = null;

	@SuppressWarnings("deprecation")
	public VelocityManagerEx() {
		String toolboxLocation = "toolbox.xml";
		if (DefaultSettings
				.isSet(StrutsConstants.STRUTS_VELOCITY_TOOLBOXLOCATION)) {
			toolboxLocation = DefaultSettings
					.get(StrutsConstants.STRUTS_VELOCITY_TOOLBOXLOCATION);
		}
		if (toolboxLocation != null) {
			try {
				ClassPathResource resource = new ClassPathResource(
						toolboxLocation);
				InputStream in = resource.getInputStream();
				try {
					XMLToolboxManager mgr = new XMLToolboxManager();
					mgr.load(in);
					toolboxManager = mgr;
				} finally {
					try {
						in.close();
					} catch (IOException e) {
						log.warn("failed to close input stream: "
								+ toolboxLocation);
					}
				}
			} catch (Exception ex) {
				log.error("failed to load toolbox: " + toolboxLocation, ex);
			}
		}
		synchronized (this) {
			instance = this;
		}
	}

	public synchronized static VelocityManagerEx getInstance() {
		if (instance == null) {
			new VelocityManagerEx();
		}
		return instance;
	}

	protected void initToolbox(ServletContext context) {

	}

	public ToolboxManager getToolboxManager() {
		return toolboxManager;
	}

}
